<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>
  <div>
    <video style="display: none;" id="video"></video>
    <canvas id="canvas"></canvas>
    <!--  <canvas id="canvas" style="display: none"></canvas>-->
    <script>
      
      const width = 800;
      const height = 400;
      const video = document.getElementById('video');
      //访问摄像头
      if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        //调用用户媒体设备, 访问摄像头
        getUserMedia();
      } else {
        alert('不支持访问用户媒体');
      }

      //访问用户媒体设备的兼容方法
      function getUserMedia (constraints) {
        let obj = {}
        if (constraints) {
          obj.deviceId = constraints
        }
        obj.video = true
        obj.width = width
        obj.height = height
        if (navigator.mediaDevices.getUserMedia) {
          //最新的标准API
          navigator.mediaDevices.getUserMedia(obj).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
          //webkit核心浏览器
          navigator.webkitGetUserMedia(obj, success, error)
        } else if (navigator.mozGetUserMedia) {
          //firfox浏览器
          navigator.mozGetUserMedia(obj, success, error);
        } else if (navigator.getUserMedia) {
          //旧版API
          navigator.getUserMedia(obj, success, error);
        }
      }
      //成功回调
      function success (stream) {
        //兼容webkit核心浏览器
        // const CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        // video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
        setInterval(drawCanvasImage, 10)
      }

      //失败回调
      function error (error) {
        console.log("访问用户媒体设备失败", error);
      }

      function drawCanvasImage () {
        const canvas = document.getElementById('canvas');
        canvas.width = width;
        canvas.height = height;
        const context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, width, height, 0, 0, width, height);
        //获取图片，数据格式为base64
        imageData = canvas.toDataURL("image/png");
      }
      // base64转文件
      function dataURLtoFile () {
        if (imageData) {
          let arr = imageData.split(",");
          let mime = arr[0].match(/:(.*?);/)[1];
          let bstr = atob(arr[1]);
          let n = bstr.length;
          let u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          let blob = new File([u8arr], 'file', { type: mime });
          return blob
        }
      }
    </script>

  </div>
</body>

</html>